package com.smart.thirteen.namedParameter;

import com.smart.thirteen.Topic;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.rowset.SqlRowSet;

/**
 * @author junrui.wang
 * @create 2019/10/21
 */
public class NamedParameterJdbcTemplateTest {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath*:com/smart/thirteen/applicationContext-template.xml");
        NamedParameterJdbcTemplate namedParameterJdbcTemplate = (NamedParameterJdbcTemplate) ac.getBean("namedParameterJdbcTemplate");

        Topic topic = new Topic();
        topic.setUser_id("2");
        topic.setTopic_title("test2");
        String sql = "INSERT INTO t_topic(topic_title, user_id) VALUES (:topic_title, :user_id)";
        //有领域对象
        SqlParameterSource sqlParameterSource = new BeanPropertySqlParameterSource(topic);
        namedParameterJdbcTemplate.update(sql, sqlParameterSource);

        //没有领域对象，使用MapSqlParameterSource
        MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource();
        mapSqlParameterSource.addValue("topic_title", topic.getTopic_title());
        mapSqlParameterSource.addValue("user_id", topic.getUser_id());
        namedParameterJdbcTemplate.update(sql, mapSqlParameterSource);

    }
}
